<?php

namespace app\common\func;

use app\common\model\AppMenu;
use app\common\model\Money;
use app\common\model\MoneyCash;
use app\common\model\MoneyFlow;
use app\common\model\MoneyProfit;
use app\common\model\MoneyStandard;
use think\Db;

class Balance
{

    //查询用户总余额
    public static function getTotal($mainType, $mainId)
    {
        return Money::where(["main_type" => $mainType, "main_id" => $mainId])->sum("money");
    }

    //查询用户各交易类型总余额
    public static function getTypeTotal($mainType, $mainId)
    {
        return Db::name("money")->alias("m")
            ->join("balance_type b", "m.balance_type_id = b.id", "LEFT")
            ->where(["m.main_type" => $mainType, "m.main_id" => $mainId])
            ->field("SUM(money) as total,b.name,b.id as balance_type_id")
            ->group("m.balance_type_id")
            ->select();
    }

    //查询用户各交易类型（基础、隐形）总余额
    public static function getTypePart($mainType, $mainId, $balanceType)
    {
        return Db::name("money")->alias("m")
            ->join("balance_type b", "m.balance_type_id = b.id", "LEFT")
            ->where(["m.main_type" => $mainType, "m.main_id" => $mainId, "m.balance_type_id" => $balanceType])
            ->field("SUM(m.money) as total,m.type,b.id as balance_type_id")
            ->group("m.type")
            ->select();
    }

    public static function getMoneyDetails($mainType, $mainId, $balanceType, $moneyType, $pageSize, $startTime = 0, $endTime = 0, $sn = "")
    {
        switch ($balanceType) {
            case 1:
                $table = "money_profit";
                break;
            case 2:
                $table = "money_cash";
                break;
            case 3:
                $table = "money_flow";
                break;
            case 4:
                $table = "money_standard";
                break;
            default:
                return [];
        }

        $query = Db::name($table)->alias("m")
            ->join("product p", "m.product_id = p.id", "LEFT")
            ->where(["m.main_type" => $mainType, "m.main_id" => $mainId, "m.money_type" => $moneyType]);

        if ($startTime > 0 && $endTime > 0) {
            $query->where(["m.trading_time" => [">=", $startTime]])->where(["m.trading_time" => ["<=", $endTime]]);
        }

        if (isset($sn) && $sn != "") {
            $query->where(["m.sn" => ["like", "%" . $sn . "%"]]);
        }

        return $query->order("m.trading_time desc,m.id desc")->field("m.*,FROM_UNIXTIME(m.trading_time,'%Y-%m-%d %H:%i') as time,p.id as product_id,p.name as product_name")->paginate($pageSize);
    }

    public static function getMoneyLogs($mainType, $mainId, $pageSize, $balanceType = 0, $moneyType = "", $sn = "", $startTime = 0, $endTime = 0, $productId = 0)
    {
        $query = Db::name("money_log")->alias("m")
            ->join("product p", "m.product_id = p.id", "LEFT")
            ->where(["m.main_type" => $mainType, "m.main_id" => $mainId]);

        if ($productId > 0) {
            $query->where(["m.product_id" => $productId]);
        }

        if ($balanceType > 0) {
            $query->where(["m.balance_type_id" => $balanceType]);
        }

        if ($moneyType != "") {
            $query->where(["m.money_type" => $moneyType]);
        }

        if ($sn != "") {
            $query->where(["m.sn" => ["like", "%" . $sn . "%"]]);
        }

        if ($startTime > 0 && $endTime > 0) {
            $query->where(["m.trading_time" => [">=", $startTime]])->where(["m.trading_time" => ["<=", $endTime]]);
        }

        return $query->order("m.trading_time desc,m.id desc")->field("m.*,FROM_UNIXTIME(m.trading_time,'%Y-%m-%d %H:%i') as time,p.id as product_id,p.name as product_name")->paginate($pageSize);
    }


    // ["id"] =&gt; int(10656)
    // ["main_type"] =&gt; int(2)
    // ["main_id"] =&gt; int(45)
    // ["balance_type_id"] =&gt; int(1)
    // ["money_type"] =&gt; string(4) "base"
    // ["sn"] =&gt; string(20) "00002402009891352313"
    // ["type"] =&gt; int(1)
    // ["before"] =&gt; string(7) "1372.56"
    // ["changes"] =&gt; string(4) "0.41"
    // ["after"] =&gt; string(7) "1372.97"
    // ["mome"] =&gt; string(12) "分润收益"
    // ["status"] =&gt; int(1)
    // ["table_name"] =&gt; string(20) "transaction_data_sft"
    // ["order_num"] =&gt; string(10) "1395381649"
    // ["company_id"] =&gt; int(1)
    // ["product_id"] =&gt; int(3)
    // ["policy_id"] =&gt; int(1)
    // ["merchant_name"] =&gt; string(5) "李**"
    // ["tran_amount"] =&gt; string(7) "1385.00"
    // ["is_withdrawal"] =&gt; int(0)
    // ["trading_time"] =&gt; int(1697333211)
    // ["create_time"] =&gt; int(1697333285)
    // ["time"] =&gt; string(16) "2023-10-15 09:26"
    // ["product_name"] =&gt; string(18) "盛付通 - 电签"

    /**
     * 分红交易
     */
    public static function bonus_money_logs($id)
    {
        $query = Db::name("bonus_details")
            ->where("id = {$id}")
            ->field("*,lev_code product_name,earns changes,6 balance_type_id,FROM_UNIXTIME(create_time,'%Y-%m-%d') as time")
            ->select();
        foreach ($query as $k => $v) {
            $query[$k]["product_name"] = date("Y年m月", $v["times"]) . "份" . $v["product_name"] . "阶段,分红金额" . $v["money"] . "，达标" . $v["per_nums"] . "人，人均收入" . $v["changes"];
            $query[$k]['mome'] = '分红收益';
        }
        return $query;
    }

    /**
     * 分红 - 详情
     */
    public static function bonus_monay_details($id,  $startTime = 0, $endTime = 0)
    {


        $query = Db::name("bonus_details")
            ->where("agid = {$id} and (create_time >= {$startTime} and  create_time <= {$endTime})")
            ->field("*,lev_code product_name,earns changes,6 balance_type_id,FROM_UNIXTIME(create_time,'%Y-%m-%d') as time")
            ->select();
        foreach ($query as $k => $v) {
            $query[$k]["product_name"] = date("Y年m月", $v["times"]) . "份" . $v["product_name"] . "阶段,分红金额" . $v["money"] . "，达标" . $v["per_nums"] . "人，人均收入" . $v["changes"];
            $query[$k]['mome'] = '分红收益';
        }
        return $query;
    }

    /**
     * 分红 - 首月 - 统计
     */
    public static function bonus_home_total($id,  $st, $en)
    {
        $sum = 0;
        if ($id) {
            $sum = Db::name("bonus_details")
                ->where("agid = {$id} and (create_time >= " . strtotime($st) . " and  create_time <= " . strtotime($en) . ")")
                ->sum("earns");
        }
        return $sum;
    }

    public static function balance($id)
    {
        if ($id) {
            $isReals = Db::name("user")->where("id =" . $id)->value("is_virtual");
            if ($isReals &&  $isReals == 2) {
                return Db::name("balance_virtual")->where("main_id = " . $id)->value("money");
            }
        }
        return false;
    }
}
